package com.wzy.business.store.login

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.text.TextUtils
import android.view.View
import android.webkit.JavascriptInterface
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.TextView
import androidx.appcompat.app.AppCompatDialog
import androidx.core.content.ContextCompat
import androidx.lifecycle.MutableLiveData
import com.allenliu.versionchecklib.v2.AllenVersionChecker
import com.allenliu.versionchecklib.v2.builder.UIData
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.EncryptUtils
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.RegexUtils
import com.blankj.utilcode.util.Utils
import com.wangzhenyu.common.util.exts.singleClick
import com.wzy.business.store.login.bean.LoginRequest
import com.wzy.business.store.login.bean.CaptchaAli
import com.wangzhenyu.common.base.BaseVBPActivity
import com.wangzhenyu.common.base.IConstant
import com.wangzhenyu.common.base.bean.LoginInfo
import com.wangzhenyu.common.base.bean.UserManager
import com.wangzhenyu.common.net.BaseResponse
import com.wangzhenyu.common.netcore.coroutine.CoroutineSupport
import com.wangzhenyu.common.util.DialogUtils
import com.wzy.business.R
import com.wzy.business.databinding.BusinessActivityLoginBinding
import com.wzy.business.store.login.presenter.LoginPresenter
import com.wzy.business.store.login.presenter.impl.LoginPresenterImpl
import com.wzy.business.store.main.UserServiceH5Activity
import com.wzy.business.store.me.ForgetPasswordActivity
import com.wzy.business.store.me.bean.AccountSetting
import com.wzy.business.util.OtherUtils
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.util.Locale

class LoginActivity : BaseVBPActivity<BusinessActivityLoginBinding, LoginPresenter>(),
    LoginPresenter.View {

    companion object {
        //三种登陆方式
        //短信
          const val LOGIN_BY_CODE = 0

        //密码
          const val LOGIN_BY_PASSWORD = 1

        //注册
        private const val REGISTER = 2

        //获得是否同意协议的结果
        private const val REQUEST_CODE_SERVICE = 8
    }

    private var registerStatus = false

    //登陆方式
    private var loginType = LOGIN_BY_PASSWORD

    private val mCoroutine: CoroutineSupport by lazy { CoroutineSupport() }

    private var versionUpdateDialog: AppCompatDialog? = null
    private var accountSetting: AccountSetting? = null

    override fun useBaseLayout() = false

    override fun getViewBinding() = BusinessActivityLoginBinding.inflate(layoutInflater)

    override fun createPresenter() = LoginPresenterImpl(this)

    private val captchaAli: MutableLiveData<CaptchaAli> = MutableLiveData()

    override fun initView() {

        //状态栏
        BarUtils.setStatusBarColor(context, ContextCompat.getColor(context, R.color.colorPrimary))

        //页面加上测试二字
        //建议用BuildConfig.VERSION_NAME
        if (!IConstant.official) {
            findViewById<TextView>(R.id.tvVersionFlag).text = String.format(
                "测试-%s",
                "1.0"
            )
        }

        mBinding.apply {

            //获取验证码
            tvGetCode.singleClick {
                if (TextUtils.isEmpty(etPhone.text.toString())) {
                    showToast("请输入手机号码")
                    return@singleClick
                }
                if (!RegexUtils.isMobileSimple(etPhone.text.toString())) {
                    showToast("请输入正确的手机号码")
                    return@singleClick
                }
                rlLoginCaptcha.visibility = View.VISIBLE
                //无论文档的修改时间是什么，或者有没有缓存，它都会从新在服务器端请求一次来更新到页面。
                wvCaptcha.loadUrl("javascript:window.location.reload( true )")
            }

            //关闭获取验证码界面
            ivLoginCaptchaClose.setOnClickListener {
                rlLoginCaptcha.visibility = View.GONE
            }

            //登陆
            tvLogin.setOnClickListener {
                if (registerStatus) {
                    register()
                } else {
                    login()
                }
            }

            //密码登陆和验证码登陆切换
            tvBottomRight.setOnClickListener {
                changeLoginType()
            }
            //注册账号
            tvLoginHint.setOnClickListener {
                changeLoginRegister()
            }
            //查看用户协议
            tvService.setOnClickListener {
                UserServiceH5Activity.service(this@LoginActivity, REQUEST_CODE_SERVICE)
            }
            //查看隐私政策
            tvPrivacy.setOnClickListener {
                UserServiceH5Activity.privacy(this@LoginActivity, REQUEST_CODE_SERVICE);
            }
            //忘记密码
            tvForgetPassword.setOnClickListener {
                ActivityUtils.startActivity(ForgetPasswordActivity::class.java)
            }
            //登陆页面状态切换
            initLoginTypeView()
            //初始化验证码页面
            initCaptcha()

            mPresenter?.requestAccountSettingData()
        }

        initObserver()


    }

    @Deprecated("Deprecated in Java")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE_SERVICE && resultCode == Activity.RESULT_OK) {
            mBinding.ivService.isChecked = true
        }
    }


    private fun changeLoginRegister() {
        registerStatus = !registerStatus
        if (registerStatus) {
            loginType = REGISTER
        } else {
            loginType = LOGIN_BY_CODE
        }
        initLoginTypeView()
    }

    private fun initObserver() {

        captchaAli.observe(this)
        {
            it.mobile = mBinding.etPhone.text.toString()

            //获取验证码倒计时
            doGetCodeTextAction()

            if (registerStatus) {
                mPresenter?.getRegisterSmsCode(it)
            } else {
                mPresenter?.getLoginSmsCode(it)
            }
        }
    }

    private fun initLoginTypeView() {
        mBinding.apply {
            viRegisterDivide.visibility = View.GONE
            llPhone.visibility = View.GONE
            llCode.visibility = View.GONE
            llAccount.visibility = View.GONE
            llPassword.visibility = View.GONE
            tvForgetPassword.visibility = View.GONE
            tvBottomRight.visibility = View.GONE

            tvLoginType.text = getString(R.string.login_by_phone)
            tvLoginHint.text = getString(R.string.no_account_register)
            tvLogin.text = "登录"
            etPassword.hint = "请输入密码"
            etPassword.setText("")
            etCode.setText("")
            etPhone.setText("")
            etAccount.setText("")
            hintLoginTv.text = "使用已注册得手机号登录"

            if (loginType == LOGIN_BY_CODE) {
                //短信登陆
                llPhone.visibility = View.VISIBLE
                llCode.visibility = View.VISIBLE

                tvForgetPassword.visibility = View.VISIBLE
                tvBottomRight.visibility = View.VISIBLE
                tvBottomRight.text = "密码登录"
            } else if (loginType == LOGIN_BY_PASSWORD) {
                //密码登陆
                llAccount.visibility = View.VISIBLE
                llPassword.visibility = View.VISIBLE


                tvForgetPassword.visibility = View.VISIBLE
                tvBottomRight.visibility = View.VISIBLE
                tvBottomRight.text = "短信登录"
            } else if (loginType == REGISTER) {
                //注册
                viRegisterDivide.visibility = View.VISIBLE
                llPhone.visibility = View.VISIBLE
                llCode.visibility = View.VISIBLE
                llPassword.visibility = View.VISIBLE

                tvLoginType.text = getString(R.string.register_by_phone)
                tvLoginHint.text = getString(R.string.has_account_login)
                tvLogin.text = "注册"
                etPassword.hint = "请设置密码"
                hintLoginTv.text = "注册后可免费体验C店全部解决方案"
            }
        }
    }

    @SuppressLint("SetTextI18n")
    private fun doGetCodeTextAction() {

        mBinding.apply {
            tvGetCode.isEnabled = false
            mCoroutine.launch {
                var againTime = 60
                while (againTime > 0) {
                    againTime -= 1
                    tvGetCode.text = againTime.toString() + "秒"
                    delay(1000)
                }
                tvGetCode.text = getString(R.string.get_code)
                tvGetCode.isEnabled = true
            }
        }


    }

    private fun changeLoginType() {
        if (loginType == LOGIN_BY_CODE) {
            loginType = LOGIN_BY_PASSWORD
        } else if (loginType == LOGIN_BY_PASSWORD) {
            loginType = LOGIN_BY_CODE
        }
        initLoginTypeView()
    }

    private fun register() {
        mBinding.apply {
            if (TextUtils.isEmpty(etPhone.text.toString())) {
                showToast("请输入手机号码")
                return
            }
            if (!RegexUtils.isMobileSimple(etPhone.text.toString())) {
                showToast("请输入正确的手机号码")
                return
            }
            if (TextUtils.isEmpty(etCode.text.toString())) {
                showToast("请输入验证")
                return
            }

            if (TextUtils.isEmpty(etPassword.text.toString())) {
                showToast("请输入密码")
                return
            }
            if (!ivService.isChecked) {
                showToast("请同意服务条款")
                return
            }
            showDialogLoading()
            val account = etPhone.text.toString()
            mPresenter?.register(
                etPhone.text.toString(),
                EncryptUtils.encryptMD5ToString(etPassword.text.toString())
                    .lowercase(Locale.ROOT),
                etCode.text.toString(),
                account
            )
        }

    }

    private fun login() {
        mBinding.apply {
            if (loginType == LOGIN_BY_CODE) {
                if (TextUtils.isEmpty(etPhone.text.toString())) {
                    showToast("请输入手机号码")
                    return
                }
                if (!RegexUtils.isMobileSimple(etPhone.text.toString())) {
                    showToast("请输入正确的手机号码")
                    return
                }
                if (TextUtils.isEmpty(etCode.text.toString())) {
                    showToast("请输入验证")
                    return
                }
            } else {
                if (TextUtils.isEmpty(etAccount.text.toString())) {
                    showToast("请输入账号/手机号")
                    return
                }
                if (TextUtils.isEmpty(etPassword.text.toString())) {
                    showToast("请输入密码")
                    return
                }
            }
            if (!ivService.isChecked) {
                showToast("请同意服务条款")
                return
            }
            val loginInfo = LoginRequest(
                loginType,
                etPhone.text.toString(),
                EncryptUtils.encryptMD5ToString(etPassword.text.toString())
                    .lowercase(Locale.ROOT),
                etCode.text.toString(),
                etAccount.text.toString()
            )
            showDialogLoading()
            mPresenter?.login(loginInfo)
        }
    }


    @SuppressLint("SetJavaScriptEnabled")
    private fun initCaptcha() {
        mBinding.apply {
            // 设置屏幕自适应。
            wvCaptcha.settings.useWideViewPort = true
            wvCaptcha.settings.loadWithOverviewMode = true
            // 建议禁止缓存加载，以确保在攻击发生时可快速获取最新的滑动验证组件进行对抗。
            wvCaptcha.settings.cacheMode = WebSettings.LOAD_NO_CACHE
            wvCaptcha.webViewClient = object : WebViewClient() {
                @Deprecated("Deprecated in Java")
                override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
                    view.loadUrl(url)
                    return true
                }
            }
            wvCaptcha.settings.javaScriptEnabled = true
            wvCaptcha.addJavascriptInterface(this@LoginActivity, "android")
            //这里加载一个向右滑动验证的网址
            wvCaptcha.loadUrl(IConstant.getCaptchaUrl())
        }
    }

    //Android调用js方法，如果在onCreate方法中调用，js是不会执行的，需要延迟加载，哪怕只是1毫秒
    @JavascriptInterface
    fun getSlideData(callData: String?) {
        mBinding.apply {
            wvCaptcha.postDelayed({

                //关闭获取验证码页面
                rlLoginCaptcha.visibility = View.GONE

                //获取CaptchaAli
                if (!TextUtils.isEmpty(callData)) {
                    val bean = GsonUtils.fromJson(callData, CaptchaAli::class.java)
                    bean.session_id = bean.sessionid
                    captchaAli.value = bean
                }

            }, 1000)
        }

    }


    override fun onLoginSmsCodeSuccess() {
        showToast("验证码:1111")
    }

    override fun onLoginSmsCodeError(body: BaseResponse?) {
        showToast("验证码:1111")
    }

    override fun onLoginSuccess(body: LoginInfo?) {
        hideDialogLoading()
        UserManager.setLoginInfo(body!!)
        OtherUtils.goToMainActivity()
        finish()
    }

    override fun onLoginError() {
        hideDialogLoading()
        showToast("该号码未注册")
    }

    override fun onRegisterSmsCodeSuccess() {
        showToast("验证码:1111")
    }

    override fun onRegisterSmsCodeError() {
        showToast("验证码:1111")
    }

    override fun onRegisterSuccess(body: LoginInfo?) {
        hideDialogLoading()
        UserManager.setLoginInfo(body!!)
        OtherUtils.goToMainActivity()
        finish()
    }

    override fun onRegisterError() {
        hideDialogLoading()
    }

    override fun onAccountSettingSuccess(bean: AccountSetting) {
        accountSetting = bean
        if (!bean.needUpgrade) return
        versionUpdateDialog = DialogUtils.showVersionUpdateDialog(
            this, "版本更新", bean.upgradeContent ?: "", null,
            {
                val builder = AllenVersionChecker
                    .getInstance()
                    .downloadOnly(crateUIData(bean))
                builder.isDirectDownload = true
                builder.isShowNotification = false
                builder.isShowDownloadingDialog = true
                builder.isShowDownloadFailDialog = false
//                builder.downloadAPKPath = PathUtils.getExternalAppFilesPath() +"/new.apk"
                builder.executeMission(Utils.getApp())
            }, bean.castUpdate
        )
    }

    override fun onAccountSettingError(code: Int) {

    }

    private fun crateUIData(bean: AccountSetting): UIData? {
        return UIData.create().setTitle("版本更新").setContent(bean.upgradeContent)
            .setDownloadUrl(bean.downloadUrl)
    }


}